import axios from 'axios'
import Vue from 'vue'

var router:any = null
var store:any = null

function Bootstrap(_router, _store) {
  router = _router
  store = _store
  window.Log = console
  processRouter()
  processAxios()
  generateGlobalEventBus()
}

function processRouter() {
  router.beforeEach((to, from, next) => {
    if (to.matched.some(record => record.meta.requiresAuth)) {
      // this route requires auth, check if logged in
      // if not, redirect to login page.
      let isLogined = store.getters['app/isLogined']
      if (!isLogined) {
        next({
          path: '/login',
          query: {redirect: to.fullPath}
        })
      } else {
        next()
      }
    } else {
      next() // 确保一定要调用 next()
    }
  })
}

function processAxios() {
  axios.defaults.headers.common['Accept'] = 'application/json' // for all requests
  axios.interceptors.request.use(
      function (config) {
        const token = localStorage.getItem('access_token')
        config.headers.Authorization = token ? `Bearer ${token}` : ''
        return config
      },
      function (error) {
        return Promise.reject(error)
      }
  )

  axios.interceptors.response.use(
      function (response) {
        // Do something with response data
        return response
      },
      function (error) {
        // 统一处理 401 登录问题
        if (error.response.status == 401) {
          store.commit('app/LOGOUT')
          router.push('/login')
        }
        return Promise.reject(error)
      }
  )
  window.axios = axios
}

function generateGlobalEventBus() {
  class EventBus {
    constructor() {
      this.vue = new Vue()
    }

    fire(event, payload) {
      this.vue.$emit(event, payload)
    }

    on(event, cb) {
      this.vue.$on(event, cb)
    }

    off(event, cb) {
      this.vue.$off(event, cb)
    }
  }

  window.Event = new EventBus
}

var _default = Bootstrap
export default _default
